package com.doubao.device.service.impl;

import com.doubao.common.result.Result;
import com.doubao.device.dto.ApiConfigDTO;
import com.doubao.device.entity.SmartDevice;
import com.doubao.device.mapper.SmartDeviceMapper;
import com.doubao.device.service.DeviceApiService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

/**
 * 智能体API服务实现类
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class DeviceApiServiceImpl implements DeviceApiService {

    private final SmartDeviceMapper deviceMapper;
    private final RestTemplate restTemplate;

    @Value("${doubao.api.endpoint-id:ep-20241227105403-wm97s}")
    private String defaultEndpointId;

    @Value("${doubao.api.api-key:f65fcf30-0c54-45ab-9fdc-e873c81f2fdf}")
    private String defaultApiKey;

    @Value("${doubao.api.base-url:https://ark.cn-beijing.volces.com/api/v3}")
    private String defaultBaseUrl;

    @Value("${doubao.api.timeout:30}")
    private Integer defaultTimeout;

    @Value("${doubao.api.retry-times:2}")
    private Integer defaultRetryTimes;

    @Override
    public Result<ApiConfigDTO> getDeviceApiConfig(Long deviceId) {
        SmartDevice device = deviceMapper.selectById(deviceId);
        if (device == null) {
            return Result.failed("智能体不存在");
        }

        ApiConfigDTO apiConfig = new ApiConfigDTO();

        // 从设备配置中获取或使用默认值
        apiConfig.setEndpointId(device.getApiEndpointId() != null ? device.getApiEndpointId() : defaultEndpointId);
        apiConfig.setApiKey(device.getApiKey() != null ? device.getApiKey() : defaultApiKey);
        apiConfig.setBaseUrl(device.getApiBaseUrl() != null ? device.getApiBaseUrl() : defaultBaseUrl);
        apiConfig.setTimeout(device.getApiTimeout() != null ? device.getApiTimeout() : defaultTimeout);
        apiConfig.setRetryTimes(device.getApiRetryTimes() != null ? device.getApiRetryTimes() : defaultRetryTimes);

        // 设置其他信息
        apiConfig.setProviderName("豆包AI");
        apiConfig.setRequireAuth(true);
        apiConfig.setAuthType("Bearer");

        return Result.success(apiConfig);
    }

    @Override
    public Result<Void> updateDeviceApiConfig(Long deviceId, ApiConfigDTO apiConfig) {
        SmartDevice device = deviceMapper.selectById(deviceId);
        if (device == null) {
            return Result.failed("智能体不存在");
        }

        try {
            // 更新API配置
            device.setApiEndpointId(apiConfig.getEndpointId());
            device.setApiKey(apiConfig.getApiKey());
            device.setApiBaseUrl(apiConfig.getBaseUrl());
            device.setApiTimeout(apiConfig.getTimeout());
            device.setApiRetryTimes(apiConfig.getRetryTimes());

            deviceMapper.updateById(device);
            return Result.success();
        } catch (Exception e) {
            log.error("更新智能体API配置失败", e);
            return Result.failed("更新智能体API配置失败: " + e.getMessage());
        }
    }

    @Override
    public Result<Boolean> testDeviceApiConnection(Long deviceId) {
        try {
            Result<ApiConfigDTO> configResult = getDeviceApiConfig(deviceId);
            if (!configResult.isSuccess()) {
                return Result.failed(configResult.getMessage());
            }

            ApiConfigDTO apiConfig = configResult.getData();
            String testUrl = apiConfig.getBaseUrl() + "/health";

            ResponseEntity<String> response = restTemplate.getForEntity(testUrl, String.class);
            boolean isSuccess = response.getStatusCode() == HttpStatus.OK;

            return Result.success(isSuccess);
        } catch (Exception e) {
            log.error("测试智能体API连接失败", e);
            return Result.success(false);  // 返回false而不是错误，表示测试结果为失败
        }
    }

    @Override
    public ApiConfigDTO getDefaultApiConfig() {
        ApiConfigDTO defaultConfig = new ApiConfigDTO();
        defaultConfig.setEndpointId(defaultEndpointId);
        defaultConfig.setApiKey(defaultApiKey);
        defaultConfig.setBaseUrl(defaultBaseUrl);
        defaultConfig.setTimeout(defaultTimeout);
        defaultConfig.setRetryTimes(defaultRetryTimes);
        defaultConfig.setProviderName("豆包AI");
        defaultConfig.setRequireAuth(true);
        defaultConfig.setAuthType("Bearer");
        return defaultConfig;
    }
}